package com.wunu.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.wunu.annotation.AccessLimit;
import com.wunu.annotation.CurrentUser;
import com.wunu.annotation.Log;
import com.wunu.annotation.Pass;
import com.wunu.annotation.ValidationParam;
import com.wunu.base.BusinessException;
import com.wunu.base.PublicResultConstant;
import com.wunu.config.AllControllerAdvice;
import com.wunu.config.ResponseHelper;
import com.wunu.config.ResponseModel;
import com.wunu.entity.User;
import com.wunu.service.IUserService;
import com.wunu.util.Base64;
import com.wunu.util.ComUtil;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import springfox.documentation.annotations.ApiIgnore;
import sun.misc.BASE64Decoder;
import sun.util.logging.resources.logging;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.mindrot.jbcrypt.BCrypt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wunu kin
 * @since 2019-03-25
 */
@CrossOrigin
@RestController
@RequestMapping("/user")
public class UserController {
	 private static Logger logger = LoggerFactory.getLogger(AllControllerAdvice.class);
    @Autowired
    IUserService userService;


    /**
     * 获取当前登录用户信息
     * @param user
     * @return
     * @throws Exception
     */
    @GetMapping("/currentUser")
    @ApiIgnore
    public ResponseModel<User> getUser(@CurrentUser User user) throws Exception{
        return ResponseHelper.buildResponseModel(user);
    }

    @PostMapping("/mobile")
    @ApiIgnore
    public ResponseModel<String> resetMobile(@CurrentUser User currentUser,
                                            @ValidationParam("newMobile,captcha")@RequestBody JSONObject requestJson )
            throws Exception{
        userService.resetMobile(currentUser,requestJson);
        return ResponseHelper.buildResponseModel(PublicResultConstant.SUCCEED);
    }

    @PostMapping("/password")
    @ApiIgnore
    public ResponseModel<String> resetPassWord (@CurrentUser User currentUser,
            @ValidationParam("oldPassword,password,rePassword")@RequestBody JSONObject requestJson ) throws Exception{
        userService.resetPassWord(currentUser,requestJson);
        return ResponseHelper.buildResponseModel(PublicResultConstant.SUCCEED);
    }

    /**
     * 管理端修改密码
     * @return
     * @throws Exception
     */
    @ApiIgnore
    @PostMapping("/admin/password")
    public ResponseModel<String> resetPassWord (@ValidationParam("userNo,password,rePassword")
                                               @RequestBody JSONObject requestJson ) throws Exception{
        userService.resetPassWord(userService.selectById(requestJson.getString("userNo")),requestJson);
        return ResponseHelper.buildResponseModel(PublicResultConstant.SUCCEED);
    }

    @ApiImplicitParams({
        @ApiImplicitParam(name = "requestJson", value = "{\"userNo\":\"admin-e9d156955ded4990872e8a151de89dab\""
        		+ ",\"password\":\"123456\",</br>\"name\":\"kin\",\"phone\":\"13800138000\"}"
                , required = true, dataType = "String",paramType="body") })
    @PostMapping("/update")
    public ResponseModel<User> resetUserInfo (@CurrentUser User currentUser,@RequestBody JSONObject requestJson) throws Exception{
        if(!ComUtil.isEmpty(requestJson.getString("name"))){
            currentUser.setName(requestJson.getString("name"));
        }
        if(!ComUtil.isEmpty(requestJson.getString("password"))){
            currentUser.setPassword(requestJson.getString("password"));
            
        }
        if(!ComUtil.isEmpty(requestJson.getString("phone"))){
            currentUser.setPhone(requestJson.getString("phone"));
        }
        userService.updateById(currentUser);
        return ResponseHelper.buildResponseModel(currentUser);
    }
    /**
     * 修改系统用户
     * @param requestJson
     * @return
     * @throws Exception
     */
    @ApiImplicitParams({
        @ApiImplicitParam(name = "requestJson", value = "{\"userNo\":\"admin-e9d156955ded4990872e8a151de89dab\""
        		+ ",\"name\":\"kin\",\"phone\":\"13800138000\",\"status\":1}"
                , required = true, dataType = "String",paramType="body") })
    @PostMapping("/edit")
    public ResponseModel  editInfo(@RequestBody JSONObject requestJson) throws Exception{
    	User user = new User();
    	if (StringUtils.isEmpty(requestJson.getString("userNo"))) {
    		 return ResponseHelper.buildResponseModel(PublicResultConstant.PARAM_ERROR);
		}else {
			user.setUserNo(requestJson.getString("userNo"));
		}
        if(!ComUtil.isEmpty(requestJson.getString("name"))){
        	user.setName(requestJson.getString("name"));
        }
        if(!ComUtil.isEmpty(requestJson.getString("password"))&&!ComUtil.isEmpty(requestJson.getString("repassword"))){
            if (!requestJson.getString("password").equals(requestJson.getString("repassword"))) {
                throw new BusinessException(PublicResultConstant.INVALID_RE_PASSWORD);
            }
        	user.setPassword(BCrypt.hashpw(requestJson.getString("password"), BCrypt.gensalt()));
        }
        if(!ComUtil.isEmpty(requestJson.getString("endTime"))){
        	user.setEndTime(requestJson.getString("endTime"));
        }     
        if(!ComUtil.isEmpty(requestJson.getString("startTime"))){
        	user.setStartTime(requestJson.getString("startTime"));
        }
        if(!ComUtil.isEmpty(requestJson.getInteger("status"))){
        	user.setStatus(requestJson.getInteger("status"));
        } 
        if(!ComUtil.isEmpty(requestJson.getString("phone"))){
        	user.setPhone(requestJson.getString("phone"));
        }
        userService.updateById(user);
        return ResponseHelper.buildResponseModel(PublicResultConstant.SUCCEED);
    }   
    
//  @RequiresPermissions(value = {"user:list"})
    //拥有超级管理员或管理员角色的用户可以访问这个接口,换成角色控制权限,改变请看MyRealm.class
//   @RequiresRoles(value = {Constant.RoleType.SYS_ASMIN_ROLE,Constant.RoleType.ADMIN},logical =  Logical.OR)
 //   @AccessLimit(perSecond=1,timeOut = 500)//5秒钟生成一个令牌
    @ApiOperation(value="后台用户列表", notes="hander参数,需要Authorization,userName从登录用户信息中获取(like操作)",produces = "application/json")
    @ApiImplicitParams({
		@ApiImplicitParam(name = "pageIndex", value = "第几页", dataType = "String",paramType="query"),
		@ApiImplicitParam(name = "pageSize", value = "每页多少条", dataType = "String",paramType="query"),
		@ApiImplicitParam(name = "info", value = "用户名/手机号(like)" , dataType = "kin/13800138000",paramType="query")   	
			})    
    @GetMapping(value = "/pageList")
    public ResponseModel<Page<User>> findList(@CurrentUser User currentUser,@RequestParam(name = "pageIndex", defaultValue = "1", required = false) Integer pageIndex,
                                 @RequestParam(name = "pageSize", defaultValue = "10", required = false) Integer pageSize,
                                 @RequestParam(value = "info", defaultValue = "",required = false) String info) {
//    
//    	Page<User> page = userService.selectPage(new Page<>(pageIndex, pageSize),
//                ComUtil.isEmpty(userName)?new EntityWrapper<User>(): new EntityWrapper<User>().like("userName", userName).orderBy("id", true));
    	String ownerId = null;
    	String userNo =  currentUser.getUserNo();
    	if(currentUser.getParentId().equals("0")) {
    		ownerId = null;
    	}else if(currentUser.getParentId().equals("1")) {
    		ownerId = currentUser.getUserNo();
    	}else {
    		ownerId = currentUser.getParentId();
    	}
    	  Page<User> page = userService.selectPageUser(new Page<User>(pageIndex, pageSize),info,ownerId,userNo);
    	if(page.getRecords().size()>0) {
    	  page = userService.changePage(page);
    	}
        return ResponseHelper.buildResponseModel(page);
    }

    @GetMapping("/admin/infoList")
    @ApiOperation(value="获取用户列表", notes="需要header里加入Authorization")
    @ApiIgnore
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageIndex", value = "第几页"
                    , dataType = "String",paramType="query"),
            @ApiImplicitParam(name = "pageSize", value = "每页多少条"
                    , dataType = "String",paramType="query"),
            @ApiImplicitParam(name = "info", value = "会员名称或者电话"
                    , dataType = "String",paramType="query"),
            @ApiImplicitParam(name = "startTime", value = "开始时间"
                    , dataType = "Long",paramType="query"),
            @ApiImplicitParam(name = "endTime", value = "结束时间"
                    , dataType = "Long",paramType="query")
    })
    public ResponseModel findInfoList(@RequestParam(name = "pageIndex", defaultValue = "1", required = false) Integer pageIndex,
                                     @RequestParam(name = "pageSize", defaultValue = "10", required = false) Integer pageSize,
                                     //info-->用户名或者电话号码
                                     @RequestParam(name = "info", defaultValue = "", required = false) String info,
                                     @RequestParam(name = "startTime", defaultValue = "", required = false) String startTime,
                                     @RequestParam(name = "endTime", defaultValue = "", required = false) String endTime) throws Exception{
        //启用或禁用的用户
        Integer []  status= {1,2};
        //自定义分页关联查询列表
        Page<User> userPage = userService.selectPageByConditionUser(new Page<User>(pageIndex, pageSize),info,status,
                startTime,endTime);
        return ResponseHelper.buildResponseModel(userPage);
    }

    @ApiOperation(value="获取用户详细信息", notes="根据url的id来获取用户详细信息")
    @ApiImplicitParam(name = "userNo", value = "用户ID(userNo)", required = true, dataType = "String",paramType = "path")
    @GetMapping(value = "/{userNo}")
    //暂时换成了角色控制权限,改变请看MyRealm.class
    //@RequiresPermissions(value = {"user:list"})
    //拥有超级管理员或管理员角色的用户可以访问这个接口,换成角色控制权限,改变请看MyRealm.class
    //@RequiresRoles(value = {Constant.RoleType.SYS_ASMIN_ROLE,Constant.RoleType.ADMIN},logical =  Logical.OR)
    public ResponseModel<User> findOneUser(@PathVariable("userNo") String userNo) {
        User user = userService.selectById(userNo);
        return ResponseHelper.buildResponseModel(user);
    }
    

    @ApiOperation(value="用户信息", notes="body体参数,不需要Authorization",produces = "application/json")
    @ApiImplicitParam(name = "userNo", value = "用户ID(userNo)", required = true, dataType = "String",paramType = "path")
    @GetMapping("/userInfo/{userNo}")
    public ResponseModel<Map<String, Object>> userInfo(@PathVariable("userNo") String userNo) throws Exception{
        return ResponseHelper.buildResponseModel(userService.userInfo(userNo));
    }
    
    
    
    @ApiOperation(value="删除用户", notes="根据url的id来删除用户")
    @ApiImplicitParam(name = "userNo", value = "用户ID(userNo)", required = true, dataType = "String",paramType = "path")
    @DeleteMapping(value = "/{userNo}")
//    @RequiresPermissions(value = {"user:delete"})
    public ResponseModel deleteUser(@PathVariable("userNo") String userNo) throws Exception{
       userService.deleteByUserNo(userNo);
        return ResponseHelper.buildResponseModel(PublicResultConstant.SUCCEED);
    }
    
    public static void main(String[] args) {
		System.out.println(BCrypt.hashpw("123456", BCrypt.gensalt()));
	}
}

